/**
 * <li>文件名：SysUserManager.java
 * <li>说明：
 * <li>创建人： 曾明辉
 * <li>创建日期：2011-3-12
 * <li>修改人： 
 * <li>修改日期：
 */
package com.gp.sys.manager;

import java.io.Serializable;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;

import com.gp.base.BaseManager;
import com.gp.base.except.BusinessException;
import com.gp.sys.domain.SysResource;
import com.gp.sys.domain.SysRole;
import com.gp.sys.domain.SysUserRole;
import com.gp.sys.domain.SysUser;

/**
 * <li>类型名称：
 * <li>说明：
 * <li>创建人： 曾明辉
 * <li>创建日期：2011-3-12
 * <li>修改人： 
 * <li>修改日期：
 */
public class SysUserManager extends BaseManager<SysUser> implements UserDetailsService{	


	@Override
	public SysUser get(Serializable id) throws BusinessException {
		SysUser user = super.get(id);
		List<SysRole> sysRoles = this.baseDao.find(id, "SysUserRole.findSysRole");
		user.setSysRoles(sysRoles);
		
		return user;
	}

	@Override
	public SysUser insert(SysUser entity) throws BusinessException {
		super.insert(entity);
		
		this.insertUserRole(entity);//插入UserRole关系表
		
		return entity;		
	}

	@Override
	public SysUser update(SysUser entity) throws BusinessException {
		super.update(entity);
		
		this.baseDao.delete("SysUserRole.deleteByUserId", entity.getId());//删除关系
		this.insertUserRole(entity);//插入UserRole关系表
		
		return entity;		
	}


	@Override
	public void deleteByIds(Serializable... ids) throws BusinessException {
		super.deleteByIds(ids);
		this.baseDao.delete("SysUserRole.deleteByUserId", ids);//删除关系
	}
	
	@Override
	protected void checkDelete(Serializable id) throws BusinessException {
		
	}

	@Override
	protected void checkUnique(SysUser entity) throws BusinessException {
		
	}
	
	/**
	 * 
	 * <li>方法名：insertUserRole
	 * <li>@param entity
	 * <li>返回类型：void
	 * <li>说明：插入SysUserRole关系表
	 * <li>创建人：曾明辉
	 * <li>创建日期：2011-3-12
	 * <li>修改人： 
	 * <li>修改日期：
	 */
	private void insertUserRole(SysUser entity){
		for (SysRole role : entity.getSysRoles()) {
			SysUserRole userRole = new SysUserRole();
			userRole.setUserId(entity.getId());
			userRole.setRoleId(role.getId());
			this.baseDao.insert(userRole);
		}
	}

	@Override
	public UserDetails loadUserByUsername(String regNo)
			throws UsernameNotFoundException, DataAccessException {
		SysUser user = (SysUser)this.baseDao.findOne(regNo, "SysUser.findByRegNo");
        
		if(user == null) {   
            throw new UsernameNotFoundException("User【" + regNo + "】没有授权");   
        }   
        return user;   

	}

}
